package com.njdf.dao.daoImpl;

import com.njdf.dao.UserDao;
import com.njdf.entity.People;
import com.njdf.util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private static ResultSet rs;
    private static People p;
    @Override
    public People queryByName(String name) {
            String sql="select * from people where username=?";
            Object[] obj={name};
            rs=DBUtil.select(sql, obj);
        try {
            if (rs.next()){
                String username = rs.getString("username");
                String password = rs.getString("password");
                String password2 = rs.getString("password2");
                p=new People(username,password,password2);
            }
            return p;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            DBUtil.getClose();
        }

    }

    @Override
    public List<People> queryAll() {
        String sql="select * from people";
        rs=DBUtil.select(sql,null);
        List<People> ps=new ArrayList<>();
        try {
            while(rs.next()){
                String username = rs.getString("username");
                String password = rs.getString("password");
                String password2 = rs.getString("password2");
                p=new People(username,password,password2);
                ps.add(p);
            }
            return ps;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            DBUtil.getClose();
        }
    }

    @Override
    public Boolean insert(People people) {
        String sql="insert into people(username,password,password2) values(?,?,?)";
        Object[] obj={people.getName(),people.getPassword(),people.getPassword2()};
        return DBUtil.update(sql,obj);
    }
    @Override
    public Boolean delete(String name){
        String sql="delete from people where username=?";
        Object[] obj={name};
        return DBUtil.update(sql,obj);
    }
    @Override
    public Boolean update(People people){
        String sql="update people set password=?,password2=? where username=?";
        Object[] obj={people.getPassword(),people.getPassword2(),people.getName()};
        return DBUtil.update(sql,obj);
    }

    public boolean isExit(String name){
        return queryByName(name)==null?true:false;
    }
}
